package leetcode_2301_2400;

import com.sun.xml.internal.messaging.saaj.packaging.mime.util.LineInputStream;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class LeeCode_2375_wrong {
    public static void main(String[] args) {
        System.out.println(smallestNumber("IIIDIDDD"));
        System.out.println(smallestNumber("DDD"));
    }
    private static String smallestNumber(String pattern) {
        int n = pattern.length();
        char[] cs = pattern.toCharArray();
        TreeMap<Integer, int[]> map = new TreeMap<>();
        TreeMap<Integer, String> map2 = new TreeMap<>();
        int is = 0, ds = 10;
        int index = 0;
        while (index < n){
            while (index < n && cs[index] != 'I'){
                index++;
            }
            int start = index;
            while (index < n && cs[index] == 'I'){
                index++;
            }
            if (index - 1 >= start) {
                map.put(is++, new int[]{start, index - 1});
            }
        }
        index = 0;
        while (index < n){
            while (index < n && cs[index] != 'D'){
                index++;
            }
            int start = index;
            while (index < n && cs[index] == 'D'){
                index++;
            }
            if (index - 1 >= start) {
                map.put(is++, new int[]{start, index - 1});
            }
        }
        StringBuilder ans = new StringBuilder();
        int c = 1, count = 0;
        List<String> list = new ArrayList<>();
        while (!map.isEmpty()){
            Map.Entry<Integer, int[]> entry = map.pollFirstEntry();
            StringBuilder son = new StringBuilder();
            int s = entry.getValue()[0], e = entry.getValue()[1];
            if (cs[s] == 'I'){
                for (int i = s; i <= e; i++) {
                    son.append(c++);
                    count++;
                }
            }else {
                for (int i = s; i <= e; i++) {
                    son.insert(0, c++);
                    count++;
                }
            }
            if (count == n){
                if (cs[s] == 'I'){
                    son.append(c++);
                }else {
                    son.insert(0, c++);
                }
                count++;
            }
            map2.put(s, son.toString());
        }
        for (Integer key : map2.keySet()) {
            ans.append(map2.get(key));
        }
        return ans.toString();
    }
}
